//
//  SEGActivityLotteryRotateView.m
//  ExcellentHome
//
//  Created by 揭婧雯 on 2017/8/15.
//  Copyright © 2017年 陈区. All rights reserved.
//

#import "SEGActivityLotteryRotateView.h"

static const CGFloat totalDuration = 8.0;

@interface SEGActivityLotteryRotateView()
/*
 公共属性
 */
@property (nonatomic, copy) SEGRotateGiftBlock giftBlock;
/*
 图片展示数据源
 */
@property (nonatomic, strong)NSArray<SEGActivityLotteryPrizeModel*> *data;
/*
 选中的数据
 */
@property (nonatomic, strong)SEGActivityLotteryPrizeModel *selectedData;

/**
 谢谢参与
 */
@property (nonatomic, copy) NSString *placehoder;
@end

@implementation SEGActivityLotteryRotateView
{
    UIImageView *areaImageView; //八块分区背景
    UIImageView *backgorundView;//背景图
    UIImageView *backgorundView1;//背景图
    UIView *GiftgorundView;//承载奖品的背景
    UIButton *drawClickBtn;//点击抽奖按钮
    UIImageView *arrowView;//箭头
}

-(instancetype)initWithFrame:(CGRect)frame dataSource:(NSArray<SEGActivityLotteryPrizeModel*>*)data finished:(SEGRotateGiftBlock)block{
    if (self == [super initWithFrame:frame]) {
        _giftBlock = block;
        
        _data = data;
        [self setupUI];
    }
    return self;
}


/**
 构造函数 新增 谢谢参与缺省链接

 @author Sam
 @version 4.6.0
 */
-(instancetype)initWithFrame:(CGRect)frame dataSource:(NSArray<SEGActivityLotteryPrizeModel*>*)data placehoder:(NSString*)placehoder  finished:(SEGRotateGiftBlock)block{
    if (self == [super initWithFrame:frame]) {
        _giftBlock = block;
        _placehoder = placehoder;
        _data = data;
        [self setupUI];
    }
    return self;
}

-(void)layoutSubviews{
    [super layoutSubviews];
    
    [backgorundView1 setFrame:CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame))];
    
    [areaImageView setFrame:CGRectMake(0, 0, CGRectGetWidth(self.frame) * 0.8, CGRectGetHeight(self.frame)* 0.8)];
    areaImageView.center = backgorundView.center;
    
    [arrowView sizeToFit];
    arrowView.center = backgorundView.center;
    
    [drawClickBtn sizeToFit];
    drawClickBtn.center = backgorundView.center;
    
    GiftgorundView.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
}

-(void)setupUI{
    backgorundView1 = [[UIImageView alloc]initWithImage:[UIImage imageWithContentsOfFile:SEGPicName(@"img_activity01_discbg01")]];
    [self addSubview:backgorundView1];
    
    //背景转灯
    UIImage *img_activity01 = [UIImage imageWithContentsOfFile:SEGPicName(@"img_activity01_discbg02")];
    UIImage *img_activity02 = [UIImage imageWithContentsOfFile:SEGPicName(@"img_activity01_discbg03")];
    
    backgorundView = [[UIImageView alloc]init];
    backgorundView.animationImages = @[img_activity01,img_activity02];
    CGFloat animationDuration = 0.2;
    backgorundView.animationDuration = animationDuration;
    backgorundView.animationRepeatCount = totalDuration / animationDuration;
    [self addSubview:backgorundView];
    //[backgorundView startAnimating];
    [backgorundView setFrame:CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame))];
    //八块分区背景
    areaImageView = [[UIImageView alloc]initWithImage:[UIImage imageWithContentsOfFile:SEGPicName(@"img_activity01_circle")]];
    [self addSubview:areaImageView];
    
    GiftgorundView = [[UIImageView alloc]init];
    [self addSubview:GiftgorundView];
    
    arrowView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:SEGPicName(@"img_activity01_btn_bg")]];
    [self addSubview:arrowView];
    
    //点击抽奖按钮
    drawClickBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [drawClickBtn setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"img_activity01_btn_nor")] forState:UIControlStateNormal];
    [drawClickBtn setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"img_activity01_btn_pre")] forState:UIControlStateHighlighted];
    [drawClickBtn addTarget:self action:@selector(drawClick) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:drawClickBtn];
    
    
    [self seg_doLogicIfDataLessEight];
    
    for (int i = 0; i < 8; i ++) {
        UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,M_PI * CGRectGetHeight(self.bounds)/8,CGRectGetHeight(self.bounds)/3)];
        backView.layer.anchorPoint = CGPointMake(0.5, 1);
        backView.center = CGPointMake(CGRectGetHeight(self.bounds)/2, CGRectGetHeight(self.bounds)/2);
        CGFloat angle = M_PI * 2 / 8 * i;
        backView.transform = CGAffineTransformMakeRotation(angle);
        [GiftgorundView addSubview:backView];
        
        UILabel *lb = [[UILabel alloc]init];
        lb.text = [NSString stringWithFormat:@"%@", self.data[i].prizeName];
        lb.font = [UIFont systemFontOfSize:10];
        lb.textAlignment = NSTextAlignmentCenter;
        [lb sizeToFit];
        lb.layer.anchorPoint = CGPointMake(0.5, 1);
        [lb setFrame:CGRectMake(0, 0, M_PI * CGRectGetHeight(self.bounds)/8, lb.bounds.size.height)];
        [backView addSubview:lb];
        
        UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetWidth(lb.frame) * 0.5 - 30 * 0.5, CGRectGetMaxY(lb.frame) + 5, 30, 30)];
        
        if ([self.data[i].prizeId isEqualToString:@"-1"]) {
            imageView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_70_70")];
        }else{
            [imageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kClientImageRootURL,self.data[i].prizePic]] placeholderImage:[UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_70_70")]];
        }
        [backView addSubview:imageView];
        
        if (i % 2 == 0) {
            lb.textColor = [UIColor colorWithRed:255.0 / 255.0 green:217.0 / 255.0 blue:151.0 / 255.0 alpha:1];
        }else{
            lb.textColor = [UIColor colorWithRed:234.0 / 255.0 green:66.0 / 255.0 blue:70.0 / 255.0 alpha:1];
        }
    }
    
    
    [self stopAtMiddle];
}

/**
 * 如果数据少于8条，展示谢谢参与，并且数据平均展示 + 字体颜色动态变动
 * @author Sam
 */
-(void)seg_doLogicIfDataLessEight{
    if (self.data.count >= 8) {
        return;
    }
    NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:8];
    NSInteger index = 0;
    for (NSInteger i = 0; i < 8; i++) {
        
        SEGActivityLotteryPrizeModel *tmp = [SEGActivityLotteryPrizeModel new];
        tmp.prizeName = @"谢谢参与";
        tmp.prizeId = @"-2";
        tmp.prizePic = self.placehoder;
        
        if (self.data.count ==1) {
            if (i == 0) {
                [arrM addObject:self.data[i]];
            }else{
                [arrM addObject:tmp];
            }
        }
        if (self.data.count ==2) {
            if (i == 0 ||i == 2 ) {
                [arrM addObject:self.data[index]];
                index = index + 1;
            }else{
                [arrM addObject:tmp];
            }
        }
        if (self.data.count ==3) {
            if (i == 0 ||i == 2 ||i == 4 ) {
                [arrM addObject:self.data[index]];
                index = index + 1;
            }else{
                [arrM addObject:tmp];
            }
        }
        if (self.data.count ==4) {
            if (i == 0 ||i == 2 ||i == 4 ||i == 6 ) {
                [arrM addObject:self.data[index]];
                index = index + 1;
            }else{
                [arrM addObject:tmp];
            }
        }
        if (self.data.count ==5) {
            if (i == 0 ||i == 2 ||i == 4 ||i == 6  ||i == 7 ) {
                [arrM addObject:self.data[index]];
                index = index + 1;
            }else{
                [arrM addObject:tmp];
            }
        }
        if (self.data.count ==6) {
            if (i == 1 ||i ==3 ) {
                [arrM addObject:tmp];
            }else{
                [arrM addObject:self.data[index]];
                index = index + 1;
            }
        }
        if (self.data.count ==7) {
            if (i == 1) {
                [arrM addObject:tmp];
            }else{
                [arrM addObject:self.data[index]];
                index = index + 1;
            }
        }
        if (self.data.count ==8) {
            [arrM addObject:self.data[i]];
        }
    }
    self.data = [NSArray arrayWithArray:arrM];
}

-(void)drawClick{
     [backgorundView startAnimating];
    if (self.giftBlock) {
        self.giftBlock(nil , YES);
    }
}

// 旋转
- (void)rotate:(NSString*)data
{
    NSInteger index = 0;
    for (NSInteger i = 0; i < self.data.count; i++) {
        if ([data isEqualToString:@"-1"]) {//没有中奖
//            t = [self.data[i].prizeId isEqualToString:@"-2"] ? i : 0;
            if ([self.data[i].prizeId isEqualToString:@"-2"]) {
                index = i;
                break;
            }
        }else{
//            t = [self.data[i].prizeId isEqualToString:data] ? i : 0;
            if ([self.data[i].prizeId isEqualToString:data]) {
                index = i;
                break;
            }
        }
    }
    NSInteger t = self.data.count - ((index != 0 && index < self.data.count) ? index : self.data.count);
    CGFloat perAngle = t * (M_PI/4);
    CABasicAnimation* rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: perAngle + M_PI * 2];
    rotationAnimation.duration = totalDuration;
    rotationAnimation.cumulative = YES;
    rotationAnimation.delegate = self;
    rotationAnimation.speed = 5;
    rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    rotationAnimation.fillMode=kCAFillModeForwards;
    rotationAnimation.removedOnCompletion = NO;
    [GiftgorundView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
    [areaImageView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
    self.selectedData = self.data[t];
    
}

-(void)stopAtMiddle{
    CGFloat perAngle =  (M_PI/8);
    CABasicAnimation* rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: perAngle];
    rotationAnimation.duration = 0.01f;
    //rotationAnimation.cumulative = YES;
    //rotationAnimation.delegate = self;
    rotationAnimation.speed = 20;
    //rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    rotationAnimation.fillMode=kCAFillModeForwards;
    rotationAnimation.removedOnCompletion = NO;
    [GiftgorundView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
    [areaImageView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}

-(int)getRandomNumber:(int)from to:(int)to
{
    return (int)(from + (arc4random() % (to - from + 1)));
}

- (void)animationDidStart:(CAAnimation *)anim{
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    __weak typeof(self) weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (weakSelf.giftBlock) {
            weakSelf.giftBlock(weakSelf.selectedData , NO);
        }
    });
    
}

-(void)startAnimation:(NSString*)data{
    [self rotate:data];
}
@end
